﻿using System.Linq;
using AutoMapper;
using BaseAPI.BaseModel;
using Microsoft.EntityFrameworkCore;

namespace BaseAPI.BaseViewModel;

/// <summary>
/// 获取列表基类，可覆盖QueryFun方法实现where,order等查询
/// </summary>
/// <typeparam name="T">实体类型</typeparam>
public class BaseGetListViewModel<T> where T : BaseEntity
{
    /// <summary>
    /// 分页信息
    /// </summary>
    public PageRequest PageRequest { get; set; }

    /// <summary>
    /// 可覆盖实现where,order等查询，自动映射模型
    /// </summary>
    /// <param name="queryable"></param>
    /// <returns></returns>
    public virtual IQueryable<T> QueryFun(IQueryable<T> queryable)
    {
        return queryable;
    }
}

/// <summary>
/// 获取列表基类，可覆盖QueryFun方法实现where,order等查询
/// </summary>
/// <typeparam name="T">实体类型</typeparam>
/// <typeparam name="TU">任意可New类型</typeparam>
public class BaseGetListViewModel<T, TU> where T : BaseEntity
{
    /// <summary>
    /// 分页信息
    /// </summary>
    public PageRequest PageRequest { get; set; }

    protected IMapper Mapper { get; set; }
    protected DbContext Context { get; set; }

    public void Init(IMapper mapper, DbContext dbContext)
    {
        Mapper = mapper;
        Context = dbContext;
    }

    /// <summary>
    /// 可覆盖实现where,order等查询，自动映射模型
    /// </summary>
    /// <param name="queryable"></param>
    /// <returns></returns>
    public virtual IQueryable<T> QueryFun(IQueryable<T> queryable)
    {
        return queryable;
    }

    /// <summary>
    /// 可覆盖实现string,int等基类的转换查询，一般不覆盖
    /// </summary>
    /// <param name="queryable"></param>
    /// <returns></returns>
    public virtual IQueryable<TU> TransFun(IQueryable<T> queryable)
    {
        queryable = QueryFun(queryable);
        return Mapper.ProjectTo<TU>(queryable);
    }
}